"""
腾讯云COS相关API视图
"""
import requests
from django.http import HttpResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .cos_utils import cos_uploader


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_to_cos(request):
    """
    后端上传文件到COS
    
    权限: 已登录用户
    
    参数:
        - file: 文件对象
        - folder: 存储文件夹（可选，默认zongce）
    
    返回:
        - url: COS文件访问URL
        - path: 文件在COS中的路径
    
    文件路径格式: folder/user_{user_id}/YYYYMMDD/uuid_filename
    """
    file_obj = request.FILES.get('file')
    folder = request.data.get('folder', 'zongce')
    
    if not file_obj:
        return Response({
            'code': 400,
            'message': '请上传文件'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 添加用户ID文件夹
    user_folder = f"{folder}/user_{request.user.id}"
    
    # 生成文件路径
    file_path = cos_uploader.generate_file_path(file_obj.name, user_folder)
    
    # 上传到COS
    result = cos_uploader.upload_file(file_obj, file_path)
    
    if result['success']:
        return Response({
            'code': 200,
            'message': result['message'],
            'data': {
                'url': result['url'],
                'path': result['path']
            }
        })
    else:
        return Response({
            'code': 500,
            'message': result['message']
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def proxy_download(request):
    """
    代理下载COS文件，解决跨域问题
    
    权限: 已登录用户
    
    参数:
        - url: COS文件URL
    
    返回:
        - 文件二进制流
    """
    file_url = request.GET.get('url')
    
    if not file_url:
        return Response({
            'code': 400,
            'message': '请提供文件URL'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        # 从 COS 下载文件
        response = requests.get(file_url, stream=True, timeout=30)
        response.raise_for_status()
        
        # 返回文件流
        http_response = HttpResponse(
            response.content,
            content_type=response.headers.get('Content-Type', 'application/octet-stream')
        )
        
        # 设置 CORS 头
        http_response['Access-Control-Allow-Origin'] = '*'
        http_response['Access-Control-Allow-Methods'] = 'GET'
        http_response['Access-Control-Allow-Headers'] = '*'
        
        return http_response
        
    except requests.exceptions.RequestException as e:
        return Response({
            'code': 500,
            'message': f'下载失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
